use crate::common::Date;
use crate::security;
use crate::security::stock::quote::HistoricalStockQuote;
use crate::util::http;
use anyhow::Result;
use csv::StringRecord;

/// Get stock's historical quoto data
///
/// # Arguments
/// * `code`: stock code ID.20000720
/// * `start_date`: yyyyMMdd format
/// * `end_date`: yyyyMMdd format
/// # Example
/// ```
/// let d = get_stock_quote("0601398", "20000720", "20150508")
/// ```
pub async fn get_stock_quote(
    code: &str,
    start_date: Option<Date>,
    end_date: Option<Date>,
) -> Result<Vec<HistoricalStockQuote>> {
    let mut start_date = start_date.unwrap_or(Date::days_ago(60)).as_quote_date();
    let mut end_date = end_date.unwrap_or(Date::now()).as_quote_date();
    let prefix = match &code[..1] {
        "6" => "0",
        _ => "1",
    };
    let url = format!(
        "http://quotes.money.163.com/service/chddata.html?code={}{}&start={}&end={}",
        prefix,
        code,
        start_date,
        end_date
    );
    println!("url is {}", url);
    let resp = http::get(&url).await?;
    let data = HistoricalStockQuote::parse_from_csv(&resp.data);
    Ok(data)
}
